<?php

declare(strict_types=1);

namespace tools;

use \think\facade\Env;

class jwt
{
    protected $header = [
        'typ' => 'JWT',
        'alg' => 'HS256'
    ];

    protected $playload = [
        'iss' => 'system',
        'sub' => 'user'
    ];

    private $secret;

    public function __construct()
    {
        $this->secret = Env::get('JWT_SECRET');
    }

    public function withClaim($key,  $value)
    {
        $this->playload[$key] = $value;
        return $this;
    }

    public function withAlg($t)
    {
        $this->header['alg'] = $t;
        return $this;
    }

    public function create()
    {
        if (!isset($this->playload['nbf'])) {
            $this->playload['nbf'] = time();
        }
        $this->playload['iat'] = time();

        $header = self::base64UrlEncode(json_encode($this->header));
        $playload = self::base64UrlEncode(json_encode($this->playload));
        $data = $header . '.' . $playload; // 将要编码的部分
        $signature = self::signature($data, $this->secret, $this->header['alg']);
        return $header . '.' . $playload . '.' . $signature;
    }

    public function verifyToken($token)
    {
        //分割token
        $tokens = explode('.', $token);
        if (count($tokens) != 3) {
            return false;
        }
        list($base64header, $base64payload, $sign) = $tokens;
        //获取jwt算法
        $base64decodeheader = json_decode(self::base64UrlDecode($base64header), true);
        if (empty($base64decodeheader['alg'])) {
            return false;
        }
        //签名验证
        if (self::signature($base64header . '.' . $base64payload, $this->secret, $base64decodeheader['alg']) !== $sign) {
            return false;
        }

        $payload = json_decode(self::base64UrlDecode($base64payload), true);
        //签发时间大于当前服务器时间验证失败
        if (isset($payload['iat']) && $payload['iat'] > time()) {
            return false;
        }
        //过期时间小宇当前服务器时间验证失败
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            return false;
        }
        //该nbf时间之前不接收处理该Token
        if (isset($payload['nbf']) && $payload['nbf'] > time()) {
            return false;
        }
        return $payload;
    }

    /**
     * base64UrlEncode  https://jwt.io/ 中base64UrlEncode编码实现
     * @param string $input 需要编码的字符串
     * @return string
     */
    private static function base64UrlEncode(string $input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlEncode  https://jwt.io/  中base64UrlEncode解码实现
     * @param string $input 需要解码的字符串
     * @return bool|string
     */
    private static function base64UrlDecode(string $input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * HMACSHA256签名   https://jwt.io/  中HMACSHA256签名实现
     * @param string $input 为base64UrlEncode(header).".".base64UrlEncode(payload)
     * @param string $key
     * @param string $alg   算法方式
     * @return mixed
     */
    private static function signature(string $input, string $key, string $alg = 'HS256')
    {
        $alg_config = array(
            'HS256' => 'sha256',
            'HS384' => 'sha384',
            'HS512' => 'sha512'
        );
        return self::base64UrlEncode(hash_hmac($alg_config[$alg], $input, $key, true));
    }
}
